﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using XNADota.MDX;
using System.Diagnostics;

namespace XNADota.Graphics
{
    public class SequencePlayer
    {
        private Sequence _Sequence;

        private bool _IsPlaying;
        private int _CurrentTick;
        private float _AnimateSpeed;

        public int CurrentTick
        {
            get { return _CurrentTick; }
        }

        public bool IsPlaying
        {
            get { return _IsPlaying; }
        }

        public SequencePlayer(Sequence sequence)
        {
            Debug.Assert(sequence != null);

            _Sequence = sequence;
            _CurrentTick = _Sequence.IntervalStart;
        }

        public void Reset()
        {
            _IsPlaying = false;
            _CurrentTick = _Sequence.IntervalStart;
            _AnimateSpeed = 1.0f;
        }

        public void Update(TimeSpan elapsedTime)
        {
            if (_IsPlaying)
            {
                StepForward((int)(elapsedTime.TotalSeconds * 1000 * _AnimateSpeed));
            }
        }

        public void StepForward(int steps)
        {
            _CurrentTick += steps;
            if (_CurrentTick < _Sequence.IntervalStart)
            {
                _CurrentTick = (_CurrentTick - _Sequence.IntervalStart) % (_Sequence.IntervalEnd - _Sequence.IntervalStart) +
                    _Sequence.IntervalEnd;
            }
            if (_CurrentTick >= _Sequence.IntervalEnd)
            {
                if (_Sequence.NonLooping)
                    Stop();
                else
                    _CurrentTick = (_CurrentTick - _Sequence.IntervalEnd) % (_Sequence.IntervalEnd - _Sequence.IntervalStart) +
                        _Sequence.IntervalStart;
            }
        }

        public void Start(float AnimationSpeed)
        {
            _CurrentTick = _Sequence.IntervalStart;
            _IsPlaying = true;
            this._AnimateSpeed = AnimationSpeed;
        }

        public void Stop()
        {
            Reset();
        }
    }
}
